Namespace Actions.ActionItems
    <ActionItemWordAttribute("linesplit")> _
    Public Class aiLineSplit
        Inherits ActionItem

        Private LinePerFile As Integer = 100000
        Private LineCount As Integer = 0
        Private Header As String = ""
        Private FileCount As Integer = 0
        Private FileName As String
        Private HasHeader As Boolean
        Dim OutputFile As IO.StreamWriter = Nothing

        Public Sub New(ByVal Owner As Action, ByVal Definition As Xml.XmlNode)
            MyBase.New(Owner, Definition)
        End Sub

        Private Function GetNextOutputFileName() As String
            FileCount += 1
            Return OwnerAction.Info.ResultsFolderName + "\" + _
                     IO.Path.GetFileNameWithoutExtension(FileName) + "." + _
                     FileCount.ToString + "." + _
                     IO.Path.GetExtension(FileName)
        End Function

        Public Overrides Sub Execute()
            HasHeader = Configuration.BoolAttribute("header", True)
            FileName = OwnerAction.InsertParams( _
                Configuration.Attribute("what"))

            Try
                Dim SourceFile As New IO.StreamReader(FileName)
                If SourceFile.EndOfStream Then Exit Sub

                If HasHeader Then Header = SourceFile.ReadLine
                While Not SourceFile.EndOfStream
                    LineCount += 1
                    If LineCount Mod LinePerFile = 1 Then
                        If OutputFile IsNot Nothing Then
                            OutputFile.Close()
                        End If
                        OutputFile = New IO.StreamWriter(GetNextOutputFileName())
                        If HasHeader Then
                            OutputFile.WriteLine(Header)
                        End If
                    End If
                    Dim Line As String = SourceFile.ReadLine
                    If LineCount Mod LinePerFile = 1 Then
                        OutputFile.Write(Line)
                    Else
                        OutputFile.Write(vbCrLf + Line)
                    End If
                    Threading.Thread.Sleep(1)
                End While
            Catch ex As Exception
                LogException(ex)
                Exit Sub
            End Try
        End Sub
    End Class
End Namespace

